# -*- coding: utf-8 -*-
"""
Created on Sat Jun 28 11:21:17 2014

@author: Adrien
"""

import xlrd
import DatabaseHandlerInterface as DBHi
import Tkinter
import ttk
import tkFileDialog
import DataModel as Model

class SRAInformation(DBHi.DatabasePluginInterface):
    
     def __init__(self):
        self._options={'path':''}
        self._data=None
        self._headers=[]
        self._diseases=[]
     
     def setConfigDoneFunction(self,func):
        self.configDoneFunction=func
    
     def getData(self):
         if self._data==None:
             self.readFile()
         return self._data
     
     def setDiseasesList(self,diseases):
         self._diseases=diseases
         
     def readFile(self):
        filePath=self._options['path']
        try:
         	book= xlrd.open_workbook(filePath)
        except:
		raise Exception('cannot open file')
        else:
            self._data={'genes':[],'fusions':[]}
            diffSheet=book.sheet_by_name('Diff_SRA')
            sameSheet = book.sheet_by_name('Same_SRA')
            self.extractDataFromSheet(diffSheet)
            self.extractDataFromSheet(sameSheet)
        return self._data
    
    
     def extractDataFromSheet(self,sheet):
         num=0
         for rownum in range(sheet.nrows):
                myRow = sheet.row_values(rownum)
                if num <2:
                    self._headers.append(myRow)
                else:
                    import re
                    pattern= re.compile('chr(.*):(.*)-(.*)')
                    m = pattern.match(myRow[5])
                    if m !=None:
                         chromosomA = m.group(1)
                         breakpointStartA = m.group(2)
                         breakpointEndA = m.group(3)
                    m = pattern.match(myRow[10])
                    if m !=None:
                         chromosomB = m.group(1)
                         breakpointStartB = m.group(2)
                         breakpointEndB = m.group(3)
                    geneA =Model.Gene(myRow[3],function=myRow[4],chromosome=chromosomA,disease="",locus="")
                    geneB =Model.Gene(myRow[8],function=myRow[9],chromosome=chromosomB,disease="",locus="")
                    self._data['genes'].append(geneA)
                    self._data['genes'].append(geneB)
                    fusion = Model.Fusion(myRow[3],myRow[8],breakpointA=breakpointStartA+"-"+breakpointEndA, strandA="", fusionDirectionA="",breakpointB=breakpointStartB+"-"+breakpointEndB, strandB="", fusionDirectionB="",notes="")
                    self._data['fusions'].append(fusion)
                num+=1
     def setData(self,data):
         self._data=data
    
     def getOptionPanel(self,parent):
         self.v = Tkinter.StringVar()
         self.y = Tkinter.StringVar()
         self.y.set(self._options['path'])
         self.optionPanelIn=ttk.Frame(parent)
         title = ttk.Label(self.optionPanelIn,text="SRA Information")
         label0 = ttk.Label(self.optionPanelIn,text="Database file path:")
         ent0 = ttk.Entry(self.optionPanelIn,textvariable=self.y)
         
         browseBtn = ttk.Button(self.optionPanelIn, text="Browse...",command=self.browse)
         selectBtn = ttk.Button(self.optionPanelIn, text="OK",command=self.select)
         abortBtn = ttk.Button(self.optionPanelIn, text="Cancel",command=self.optionPanelIn.destroy)
         
         title.pack()
         label0.pack()
         ent0.pack(fill=Tkinter.X)
         browseBtn.pack()
         selectBtn.pack(fill=Tkinter.X)
         abortBtn.pack(fill=Tkinter.X)
         
         self.optionPanelIn.pack(side="top", fill="both", expand=1)
         return self.optionPanelIn
    
     def browse(self):
        dir_opt = options = {}
        options['initialdir'] = self.v.get()
        options['title'] = 'Select SRA_Information.xls:'
        options['parent'] = self.optionPanelIn
        directory=tkFileDialog.askopenfilename(**dir_opt)
        if directory != None and directory!="":
            self.y.set(directory)
         
     def select(self):
         self._options['path']=self.y.get()
         self.configDoneFunction()
             
     def setConfig(self,options):
         self._options=options
     
     def getConfig(self):
         return self._options




def openFile(path,mode):
     try:
         myFileobj = open(path,mode)
         return myFileobj
     except IOError:
             raise Exception('cannot open file')  
    